package com.pb.camera;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.pb.camera.application.App;
import com.pb.camera.lock.LockPatternUtils;
import com.pb.camera.lock.LockPatternView;
import com.pb.camera.lock.LockPatternView.Cell;
import com.pb.camera.lock.LockPatternView.DisplayMode;
import com.pb.camera.utils.Constants;
import com.pb.camera.utils.Encryption;
import com.pb.camera.utils.JsonAnalyle;
import com.pb.camera.utils.uniqueID;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
//问题会有三中情况调到该页面
//不同的页面调用的地址
public class CreateGesturePasswordActivity extends Activity implements
		OnClickListener {
	private static final int ID_EMPTY_MESSAGE = -1;
	private static final String KEY_UI_STAGE = "uiStage";
	private static final String KEY_PATTERN_CHOICE = "chosenPattern";
	private LockPatternView mLockPatternView;
	private Button mFooterRightButton;
	private Button mFooterLeftButton;
	protected TextView mHeaderText;
	protected List<Cell> mChosenPattern = null;
	private String account="";
	private String email="";
	private String password="";
	private String mobile="";
	private String whereFrom="";
	private String verrification_code="";
	private String openId="";
	private String userId="";
	private String gesture;
	private boolean  flag=false;
	private Handler  handler=new Handler(){
		public void handleMessage(Message msg) {
			
			if(msg.arg2==6)
			{
			    	Toast.makeText(CreateGesturePasswordActivity.this,(String) msg.obj, Toast.LENGTH_SHORT).show();
			}				
		}	
	};


	//初始的时候的状态
	private Stage mUiStage = Stage.Introduction;
	//小型的预览图
	//private View mPreviewViews[][] = new View[3][3];
	/**
	 * The patten used during the help screen to show how to draw a pattern.
	 */
	//动画展示怎么开始绘制手势
	//可以手动屏蔽了
 	private final List<Cell> mAnimatePattern = new ArrayList<Cell>();

	/**
	 * The states of the left footer button.
	 */
	enum LeftButtonMode {
		Cancel(android.R.string.cancel, true), CancelDisabled(
				android.R.string.cancel, false), Retry(
				R.string.lockpattern_retry_button_text, true), RetryDisabled(
				R.string.lockpattern_retry_button_text, false), Gone(
				ID_EMPTY_MESSAGE, false);

		/**
		 * @param text
		 *            The displayed text for this mode.
		 * @param enabled
		 *            Whether the button should be enabled.
		 */
		LeftButtonMode(int text, boolean enabled) {
			this.text = text;
			this.enabled = enabled;
		}

		final int text;
		final boolean enabled;
	}

	/**
	 * The states of the right button.
	 */
	enum RightButtonMode {
		Continue(R.string.lockpattern_continue_button_text, true), ContinueDisabled(
				R.string.lockpattern_continue_button_text, false), Confirm(
				R.string.lockpattern_confirm_button_text, true), ConfirmDisabled(
				R.string.lockpattern_confirm_button_text, false), Ok(
				android.R.string.ok, true);

		/**
		 * @param text
		 *            The displayed text for this mode.
		 * @param enabled
		 *            Whether the button should be enabled.
		 */
		RightButtonMode(int text, boolean enabled) {
			this.text = text;
			this.enabled = enabled;
		}

		final int text;
		final boolean enabled;
	}
   
	/**
	 * Keep track internally of where the user is in choosing a pattern.
	 */
	//7种状态
	protected enum Stage {

		Introduction(R.string.lockpattern_recording_intro_header,
				LeftButtonMode.Cancel, RightButtonMode.ContinueDisabled,
				ID_EMPTY_MESSAGE, true), 
		HelpScreen(
				R.string.lockpattern_settings_help_how_to_record,
				LeftButtonMode.Gone, RightButtonMode.Ok, ID_EMPTY_MESSAGE,
				false), 
	    ChoiceTooShort(
				R.string.lockpattern_recording_incorrect_too_short,
				LeftButtonMode.Retry, RightButtonMode.ContinueDisabled,
				ID_EMPTY_MESSAGE, true), 
	FirstChoiceValid(
				R.string.lockpattern_pattern_entered_header,
				LeftButtonMode.Retry, RightButtonMode.Continue,
				ID_EMPTY_MESSAGE, false), 
	NeedToConfirm(
				R.string.lockpattern_need_to_confirm, LeftButtonMode.Cancel,
				RightButtonMode.ConfirmDisabled, ID_EMPTY_MESSAGE, true),
   ConfirmWrong(
				R.string.lockpattern_need_to_unlock_wrong,
				LeftButtonMode.Cancel, RightButtonMode.ConfirmDisabled,
				ID_EMPTY_MESSAGE, true), 
ChoiceConfirmed(
				R.string.lockpattern_pattern_confirmed_header,
				LeftButtonMode.Cancel, RightButtonMode.Confirm,
				ID_EMPTY_MESSAGE, false);

		/**
		 * @param headerMessage
		 *            The message displayed at the top.
		 * @param leftMode
		 *            The mode of the left button.
		 * @param rightMode
		 *            The mode of the right button.
		 * @param footerMessage
		 *            The footer message.
		 * @param patternEnabled
		 *            Whether the pattern widget is enabled.
		 */
		Stage(int headerMessage, LeftButtonMode leftMode,
				RightButtonMode rightMode, int footerMessage,
				boolean patternEnabled) {
			this.headerMessage = headerMessage;
			this.leftMode = leftMode;
			this.rightMode = rightMode;
			this.footerMessage = footerMessage;
			this.patternEnabled = patternEnabled;
		}

		final int headerMessage;
		final LeftButtonMode leftMode;
		final RightButtonMode rightMode;
		final int footerMessage;
		final boolean patternEnabled;
	}
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		  requestWindowFeature(Window.FEATURE_NO_TITLE); 
		setContentView(R.layout.gesturepassword_create);
		if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
          //  getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
		App.getInstance().getAllActivity().add(this);
		mLockPatternView = (LockPatternView) this
				.findViewById(R.id.gesturepwd_create_lockview);
		mHeaderText = (TextView) findViewById(R.id.gesturepwd_create_text);
		//九宫格的响应函数
		mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener);
		mLockPatternView.setTactileFeedbackEnabled(true);

		mFooterRightButton = (Button) this.findViewById(R.id.right_btn);
		mFooterLeftButton = (Button) this.findViewById(R.id.reset_btn);
		mFooterRightButton.setOnClickListener(this);
		mFooterLeftButton.setOnClickListener(this);
	//	initPreviewViews();
		//bundle 空的时候
		if (savedInstanceState == null) {
			updateStage(Stage.Introduction);
			updateStage(Stage.HelpScreen);
		} else {
			final String patternString = savedInstanceState
					.getString(KEY_PATTERN_CHOICE);
			//patternString  代表的就是上次建立的手势加密后的字符串
			if (patternString != null) {
				mChosenPattern = LockPatternUtils
						.stringToPattern(patternString);
			}
			updateStage(Stage.values()[savedInstanceState.getInt(KEY_UI_STAGE)]);
			//获取保存的密码,账户,邮箱		
			
		} 

		
		
		
	   getMessageFromActivity(getIntent().getExtras());
	}

	private void initPreviewViews() {
		
	}
	  //小的预览图
	//提示第一次设置的手势
	//防止确认的时候绘制出错
	private void updatePreviewViews() {
		//修改图片
		//为选中的状态吗
		if (mChosenPattern == null)
			return;
		for (Cell cell : mChosenPattern) {
			//mPreviewViews[cell.getRow()][cell.getColumn()]
			//	.setBackgroundResource(R.drawable.gesture_create_grid_selected);

		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(KEY_UI_STAGE, mUiStage.ordinal());
		if (mChosenPattern != null) {
			//保存第一次建立的手势
			outState.putString(KEY_PATTERN_CHOICE,
			//创建手势加密后的字符串
					LockPatternUtils.patternToString(mChosenPattern));
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (mUiStage == Stage.HelpScreen) {
				updateStage(Stage.Introduction);
				return true;
			}
		}
		if (keyCode == KeyEvent.KEYCODE_MENU && mUiStage == Stage.Introduction) {
			updateStage(Stage.HelpScreen);
			return true;
		}
		return false;
	}

	private Runnable mClearPatternRunnable = new Runnable() {
		public void run() {
			//就是九宫格显示为默认的状态
			//跟reset一样的
			mLockPatternView.clearPattern();
		}
	};
    //九宫格的响应函数
	//修改的重点
	protected LockPatternView.OnPatternListener mChooseNewLockPatternListener = new LockPatternView.OnPatternListener() {
      //开始
		public void onPatternStart() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
			patternInProgress();
		}

		public void onPatternCleared() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
		}

		public void onPatternDetected(List<Cell> pattern) {
			if (pattern == null)
				return;
			if (mUiStage == Stage.NeedToConfirm
					|| mUiStage == Stage.ConfirmWrong) {
				if (mChosenPattern == null)
					throw new IllegalStateException(
							"null chosen pattern in stage 'need to confirm");
				//确认的时候比较两次的手势是否一样
				//util里面也有一个比较的方法
				if (mChosenPattern.equals(pattern)) {
					//若是一样的确认的时候有效,就是两次的手势是一样的
					updateStage(Stage.ChoiceConfirmed);
					//手动调用右边button的onClick方法
					//并且上传用户的账号,邮件手势密码等
								
					mFooterRightButton.performClick();		
				
				} else {
					//确认的时候出错了
					//两次不一样
					updateStage(Stage.ConfirmWrong);				
				}
			} 
			//此处不包含第确认的时候只是
			//第一次绘制手势的时候
			//原因在于只要是确认的时候必定走上面的条件
			//不会走本处的条件的
			//只要是第一次绘制的时候选择的个数小于要求的最小数目
			else if (mUiStage == Stage.Introduction
					|| mUiStage == Stage.ChoiceTooShort) {
				if (pattern.size() < LockPatternUtils.MIN_LOCK_PATTERN_SIZE) {
					//绘制的手势太短了			
					updateStage(Stage.ChoiceTooShort);
				} else {
					//绘制正确的时候
					mChosenPattern = new ArrayList<Cell>(
							pattern);
					 Log.i("===", "result = " + pattern.toString());
					//第一次绘制有效
					//问题若是下次回来的状态还是
					//Stage.FirstChoiceValid那不是会走最后的else
					//结果输出异常吗
					//不会的看下面的注释
					updateStage(Stage.FirstChoiceValid);			
					//手动调用右边button的onClick方法
					//要求进行确认
				    gesture=App.getInstance().getLockPatternUtils().patternToString(pattern);
					mFooterRightButton.performClick();	
					 Log.i("===", "后面" );
				}
			} else {
				//问题总共有7中状态
				//但是本处只处理李四中难道其余三种都会导致这里的异常吗
				//不是的.实际在按钮的点击函数还会再次的更爱状态
				//最后传到这个函数的状态只有四种
				throw new IllegalStateException("Unexpected stage " + mUiStage
						+ " when " + "entering the pattern.");
			}
		}

	
		private void patternInProgress() {
			mHeaderText.setText(R.string.lockpattern_recording_inprogress);
			mFooterLeftButton.setEnabled(false);
			mFooterRightButton.setEnabled(false);
		}
		@Override
		public void onPatternCellAdded(List<Cell> pattern) {
			// TODO Auto-generated method stub
			
		}
	};
 //更改状态
	private void updateStage(Stage stage) {
		mUiStage = stage;
		//对状态的不同
		//提示消息的改变	
		if (stage == Stage.ChoiceTooShort) {
			//logo下面的textview显示提示消息
			mHeaderText.setText(getResources().getString(stage.headerMessage,
					LockPatternUtils.MIN_LOCK_PATTERN_SIZE));
		} else {
			mHeaderText.setText(stage.headerMessage);
		}
       	
		  //对状态内部的的button样式改变
		if (stage.leftMode == LeftButtonMode.Gone) {
			mFooterLeftButton.setVisibility(View.GONE);
		} else {
		//	mFooterLeftButton.setVisibility(View.VISIBLE);
			mFooterLeftButton.setText(stage.leftMode.text);
			mFooterLeftButton.setEnabled(stage.leftMode.enabled);
		}

		mFooterRightButton.setText(stage.rightMode.text);
		mFooterRightButton.setEnabled(stage.rightMode.enabled);

		// same for whether the patten is enabled
		if (stage.patternEnabled) {
			mLockPatternView.enableInput();
		} else {
			mLockPatternView.disableInput();
		}

		mLockPatternView.setDisplayMode(DisplayMode.Correct);

		
		
//状态判断的重点
//若是不想要下面的两个button
//需要在这里手动调用onclick的方法吗
		switch (mUiStage) {
		case Introduction:
			mLockPatternView.clearPattern();
			break;
		case HelpScreen:
			//展示怎么绘制的手势的动画
		//	mLockPatternView.setPattern(DisplayMode.Animate, mAnimatePattern);
			
			updateStage(Stage.Introduction);
			
			break;
		case ChoiceTooShort:
			mLockPatternView.setDisplayMode(DisplayMode.Wrong);
			postClearPatternRunnable();
			break;
		case FirstChoiceValid:
			
			break;
		case NeedToConfirm:
			//清除设置的手势
			mLockPatternView.clearPattern();
			//在小的九宫格显示第一次设置的手势
			updatePreviewViews();
			break;
		case ConfirmWrong:
			mLockPatternView.setDisplayMode(DisplayMode.Wrong);
			postClearPatternRunnable();
			break;
		case ChoiceConfirmed:
			break;
		}

	}

	
	// clear the wrong pattern unless they have started a new one
	// already
	//清理错误的样式
	private void postClearPatternRunnable() {
		mLockPatternView.removeCallbacks(mClearPatternRunnable);
		//post相当于reset
		mLockPatternView.postDelayed(mClearPatternRunnable, 2000);
	}
	//在这里面再次更改状态
	//这是非常重要的
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		//左边的按钮的点击
		case R.id.reset_btn:
			if (mUiStage.leftMode == LeftButtonMode.Retry) {
				mChosenPattern = null;
				//清理选着了的按钮
				mLockPatternView.clearPattern();
				//这个更改状态是非常重要的
				updateStage(Stage.Introduction);
			} else if (mUiStage.leftMode == LeftButtonMode.Cancel) {
				// They are canceling the entire wizard
				
				finish();
			} else {
				throw new IllegalStateException(
						"left footer button pressed, but stage of " + mUiStage
								+ " doesn't make sense");
			}
			break;
		//右边的按钮的点击
		case R.id.right_btn:
			if (mUiStage.rightMode == RightButtonMode.Continue) {
				if (mUiStage != Stage.FirstChoiceValid) {
					throw new IllegalStateException("expected ui stage "
							+ Stage.FirstChoiceValid + " when button is "
							+ RightButtonMode.Continue);
				}
				updateStage(Stage.NeedToConfirm);
			} else if (mUiStage.rightMode == RightButtonMode.Confirm) {
				if (mUiStage != Stage.ChoiceConfirmed) {
					throw new IllegalStateException("expected ui stage "
							+ Stage.ChoiceConfirmed + " when button is "
							+ RightButtonMode.Confirm);
				}
				
				//访问网络上传  手势等等的信息
				//正确绘制的手势密码的时候
				//Stage.ChoiceConfirmed
				mLockPatternView.clearPattern();
			   updateStage(Stage.Introduction);
			    
			   register(gesture);
			     		     
			} else if (mUiStage.rightMode == RightButtonMode.Ok) {
				if (mUiStage != Stage.HelpScreen) {
					throw new IllegalStateException(
							"Help screen is only mode with ok button, but "
									+ "stage is " + mUiStage);
				}
				mLockPatternView.clearPattern();
				mLockPatternView.setDisplayMode(DisplayMode.Correct);
				updateStage(Stage.Introduction);
			}
			break;
		}
	}
	
	private void getMessageFromActivity(Bundle bundle)
	{  
		//小心返回的是null
		//根据whereFrom的不同判断
		whereFrom=bundle.getString("whereFrom");
		if(whereFrom.equals("setting"))
		{		
     		email=bundle.getString("email");
			mobile=bundle.getString("mobile");
			account=bundle.getString("account");
			password=bundle.getString("password");
		}
		else if (whereFrom.equals("weixin"))
		{ 
			email=bundle.getString("email");
			mobile=bundle.getString("mobile");
			verrification_code=bundle.getString("code");
			openId=bundle.getString("openId");
	
		}
		//来自微信绑定用户后,用户没有注册手势的时候单纯的注册手势
		else  if((whereFrom.equals("only_register_gesture")))
		{
			//完全可以从applicatiion 里面获取的
			userId=bundle.getString("userId");			
		}else if (whereFrom.endsWith("log_nogesture")) {
			//来自账户登录但是没有设置手势的时候
			//设置成功之后需要打开到首页的
		}	
	}
	/**上传设置的手势
	 * @param gesture
	 */
	private  void  register(String gesture)
	{    		
		//来自注册界面
		//不是 使用微信的注册
		if(whereFrom.equals("setting"))
		{			
			try {
				password=Encryption.encode(password);
				password=URLEncoder.encode(password,"utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				Log.i("===", "无效的编码");
				e.printStackTrace();
			}		
			getCode(Constants.register(mobile, account, password, email, uniqueID.id(this), urlEncode(gesture)), this,0);		
		}
		//来自
		//微信登录,之后的注册
		else if (whereFrom.equals("weixin"))
		{ 		
		  getCode(Constants.weiXinRegister(mobile, verrification_code, email,urlEncode(openId), urlEncode(uniqueID.id(this)), urlEncode(gesture)) ,this,1);
		
		}
		//来自微信绑定用户后,用户没有注册手势的时候单纯的注册手势
		else  if((whereFrom.equals("only_register_gesture")))
		{	
		  getCode(Constants.settingGesture(urlEncode(userId), urlEncode(gesture)) ,this,2);			
		}
				
	}
	
	
	 private void   getCode(String  url,final Activity  activity,final int mode)
	  {
		   HttpUtils httpUtils = new HttpUtils();
			httpUtils.send(HttpMethod.POST, url,  new RequestCallBack<String>() {
				@Override
				public void onFailure(HttpException arg0, String arg1) {
					Toast.makeText(activity, "网络访问失败,请检查你的网络", 0).show();
					//方便用户重新进入手势页面					
					//微信注册没有走到这里
					finish();					
				}
				@Override
				public void onSuccess(ResponseInfo<String> arg0) {	
				boolean flag=JsonAnalyle.jsonAnalyse(arg0.result, CreateGesturePasswordActivity.this, null,handler);
				Log.i("123", "注册手势的结果"+arg0.result);
				if(flag)
						{
						 //此時代表註冊成功,返回的数据是否保存呢
						 //例如userid等值	 	
						if(mode==0)
						{							
							//跳转到首页面值最好的是要求用户输入刚才注册的账号的用户名密码之类的
							//使用户确定注册成功了;	
						    Map map=JsonAnalyle.registerSuccess(arg0.result);						
							updateAppUserInfo(account, password, gesture, (String)map.get("userid"), email, mobile, openId);
						    saveUserMessage(account,password, gesture,(String)map.get("userid"), email, mobile , openId);				
							//开启首页面
							saveChosenPatternAndFinish();			   
						}
						else if(mode==1)
						{//微信登录之后的注册
						    Map map=JsonAnalyle.weiXinLogSuccess(arg0.result);					
							updateAppUserInfo(account, (String) map.get("p"), gesture,(String) map.get("userid"), email, mobile, openId);
						    saveUserMessage(mobile,(String)map.get("p"), gesture,(String)map.get("userid"), email, mobile , openId);				
							//开启首页面
							saveChosenPatternAndFinish();
						}
						else 	if(mode==2)
						{			
							      //微信绑定的界面保存了,账号,密码等的信息
						           App.getInstance().setGesture(gesture);
						           SharedPreferences  pre=getSharedPreferences("itisforlife",Context.MODE_PRIVATE);		    		  
							        Editor  editor=pre.edit();
							        editor.putString("gesture",gesture);
							        editor.commit();
							    	//开启首页面
									saveChosenPatternAndFinish();											
						}					
					}	
				
				else  if(!flag)
				{					
						finish();
					  							
				}
			 }
	     });			
	  }
	  
	 
	 
	 
	 
	
	  private  void  updateAppUserInfo(String account,String password,String   gesture,String userId,String email,String mobile ,String openId)
	  {
		  App application=App.getInstance();
		  application.setAccount(account);
		  application.setOpenId(openId);
		  application.setGesture(gesture);
		  application.setPassword(urlEncode(password));
		  application.setMobile(mobile);
		  application.setEmail(email);
		  application.setUserId(userId);	  
	  }
	    
	  private  void  saveUserMessage(String account,String password,String   gesture,String userId,String email,String mobile ,String openId)
	  {
		  
		  SharedPreferences  pre=getSharedPreferences("itisforlife",Context.MODE_PRIVATE);		    		  
	       Editor  editor=pre.edit();
	       editor.putString("account",account);
	        //密码不在返回之内列
	        //自己补充的
	        editor.putString("password",urlEncode(password));	
	        editor.putString("gesture",gesture);
	        editor.putString("openid",openId);	
	        editor.putString("email",email);	
	        editor.putString("userid",userId);	
	        editor.putString("mobile",mobile);
	        editor.commit();		  
	        
	  }
	  
	  private void saveChosenPatternAndFinish() {
			startActivity(new Intent(this,HomePageActivity.class));
			finish();
	  }
	 
	  
	  private   String   urlEncode(String data)
	  {
		  String   outcome=null;
		  try {
                outcome=URLEncoder.encode(data, "utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			Log.i("===", "编码错误");
			e.printStackTrace();
		}
		  return  outcome;	  
	  }
	
	  @Override
		public void finish() {
			App.getInstance().getAllActivity().remove(this);
			super.finish();
		}
	  @Override
		protected void onDestroy() {
			App.getInstance().getAllActivity().remove(this);
			super.onDestroy();
		}
}
